import React, {useState} from 'react'
import SimpleMDE from 'react-simplemde-editor'
import {v4} from 'uuid'
import './App.css'
import 'easymde/dist/easymde.min.css'
import 'bootstrap/dist/css/bootstrap.min.css'
import {faPlus, faFileImport} from '@fortawesome/free-solid-svg-icons'

import FileSearch from './components/FileSearch'
import FileList from './components/FileList'
import BottomBtn from './components/BottomBtn'
import TabList from './components/TabList'
import {flattenArr, objToArr} from './helpers/utils'
import defaultFiles from './mock'
import fileHelper from './helpers/fileHelper'

const {join, basename, extname, dirname} = window.require('path')
// const {remote} = require('electron')
// const savedLocation = remote.app.getPath('downloads')

function App() {
  const [files, setFiles] = useState(flattenArr(defaultFiles))
  const [activeFileID, setActiveFileID] = useState('')
  const [unsavedFileIDs, setUnsavedFileIDs] = useState([])
  const [openedFileIDs, setOpenedFileIDs] = useState([])
  const [searchedFiles, setSearchedFiles] = useState([])

  const filesArr = objToArr(files)

  // const activeFile = files.find(file => file.id === activeFileID)
  const activeFile = files[activeFileID]

  // const openedFiles = openedFileIDs.map(openID => files.find(file => file.id === openID))
  const openedFiles = openedFileIDs.map(openID => files[openID])

  const filesList = searchedFiles.length > 0 ? searchedFiles : filesArr

  const fileSearch = (keyword) => {
    const newFiles = filesArr.filter(file => file.title.includes(keyword))
    setSearchedFiles(newFiles)
  }

  const fileClick = (fileID) => {
    setActiveFileID(fileID)
    !openedFileIDs.includes(fileID) && setOpenedFileIDs([...openedFileIDs, fileID])
  }

  const deleteFile = (fileID) => {
    // const newFiles = files.filter(file => file.id !== fileID)
    delete files[fileID]
    setFiles(files)
    // close the tab if opened
    tabClose(fileID)
  }
  const updateFileName = (id, title, isNew) => {
    // const newFiles = files.map(file => {
    //   if (file.id === id) {
    //     file.title = title
    //     file.isNew = false
    //   }
    //   return file
    // })
    const modifiedFile = {...files[id], title, isNew: false}
    setFiles({...files, [id]: modifiedFile})
    // if (isNew) {
    //   fileHelper.writeFile(join(savedLocation, `${title}.md`), modifiedFile.body).then(() => {
    //     setFiles({...files, [id]: modifiedFile})
    //   })
    // } else {
    //   fileHelper.renameFile(
    //     join(savedLocation, `${files[id].title}.md`),
    //     join(savedLocation, `${title}.md`)
    //   ).then(() => {
    //     setFiles({...files, [id]: modifiedFile})
    //   })
    // }
  }

  const createNewFile = () => {
    const newID = v4()
    const newFile = {
      id: newID,
      title: '',
      body: '## 请输出 Markdown',
      createdAt: new Date().getTime(),
      isNew: true,
    }
    setFiles({...files, [newID]: newFile})
  }
  const importFiles = () => {

  }

  const tabClick = (fileID) => {
    setActiveFileID(fileID)
  }
  const tabClose = (fileID) => {
    // remove current fileID from openedFileIDs
    const tabsWithout = openedFileIDs.filter(openedID => openedID !== fileID)
    setOpenedFileIDs(tabsWithout)
    tabsWithout.length > 0 ? setActiveFileID(tabsWithout[0]) : setActiveFileID('')
  }
  const fileChange = (id, value) => {
    // const newFiles = files.map(file => {
    //   file.id === id && (file.body = value)
    //   return file
    // })
    const newFile = {...files[id], body: value}
    setFiles({...files, [id]: newFile})
    // update unsavedFileIDs
    !unsavedFileIDs.includes(id) && setUnsavedFileIDs([...unsavedFileIDs, id])
  }

  return (
    <div className="App container-fluid px-0">
      <div className="row no-gutters">
        <div className="col-3 bg-light left-panel">
          <FileSearch title='我的云文档' onFileSearch={fileSearch}/>
          <FileList files={filesList} onFileClick={fileClick} onSaveEdit={updateFileName} onFileDelete={deleteFile}/>
          <div className="row no-gutters button-group">
            <div className="col">
              <BottomBtn text="新建" colorClass="btn-primary" icon={faPlus} onBtnClick={createNewFile}/>
            </div>
            <div className="col">
              <BottomBtn text="导入" colorClass="btn-success" icon={faFileImport} onBtnClick={importFiles}/>
            </div>
          </div>
        </div>
        <div className="col-9 right-panel">
          {!activeFile &&
          <div className="start-page">
            选择或者创建新的 Markdown 文档
          </div>
          }
          {activeFile &&
          <>
            <TabList files={openedFiles} activeId={activeFileID} unsavedIds={unsavedFileIDs}
                     onTabClick={tabClick} onCloseTab={tabClose}/>
            <SimpleMDE
              key={activeFile?.id}
              value={activeFile?.body}
              onChange={(value => fileChange(activeFile.id, value))}
              options={{
                spellChecker: false,
                minHeight: '600px',
              }}
            />
          </>
          }
        </div>
      </div>
    </div>
  );
}

export default App;
